package com.tencent.cloud.iov.flow.presenter.impl;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.subjects.BehaviorSubject;

/**
 * 提订阅关系管理，在销毁页面时取消所有订阅关系
 *
 * @author showxiao
 * @date 2018/10/8
 */
public abstract class BaseDisposablePresenter extends BaseActionPresenter {

    private ObservableTransformer mDisposeTransformer;
    private BehaviorSubject<Boolean> mDisposeSubject;

    protected final <T> ObservableTransformer<T, T> getDisposeTransformer() {
        if (mDisposeTransformer == null) {
            mDisposeTransformer = new ObservableTransformer<T, T>() {

                @Override
                public ObservableSource<T> apply(Observable<T> upstream) {
                    return upstream.takeUntil(getDisposeSubject());
                }
            };
        }

        return (ObservableTransformer<T, T>) mDisposeTransformer;
    }

    private ObservableSource<Boolean> getDisposeSubject() {
        if (mDisposeSubject == null) {
            mDisposeSubject = BehaviorSubject.create();
        }
        return mDisposeSubject;
    }

    @Override
    public void onDestroy() {
        if (mDisposeSubject != null) {
            mDisposeSubject.onNext(true);
            mDisposeSubject = null;
        }
        mDisposeTransformer = null;
        super.onDestroy();
    }
}
